<script setup>
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue'
import { ref ,onBeforeMount, reactive, toRefs, computed} from 'vue';
import { da } from 'element-plus/es/locales.mjs';
import { listHandler } from '../../api/generic.js';
import { deleteTableRow } from '../../utils/utils';
import Table from '../components/Table.vue';
import { object2List,list2Object } from '../../utils/utils';
// import DialogYaml from '../components/DialogYaml.vue';
// import { obj2Yaml } from '../../utils/utils';
import { updatePVHandler as updateHandler, createPVHandler as createHandler } from '../../api/pv';
import {useRouter} from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})

const data = reactive({
  clusterId: '',
  namespace: '',
  item: {
    apiVersion: 'v1',
    kind: 'PersistentVolume',
    metadata: {
      name: '',
      labels: {},
      annotations: {}
    },
    spec: {
      capacity: {
        storage: '5Gi',
      },
      storageClassName: '',
      accessModes: ['ReadWriteMany'],
      persistenceVolumeReclaimPolicy : 'Retain',
      nfs :{
        server: '',
        path: '',
        readOnly: false,
      }
    }

    },
  options: {
    pvType: 'nfs',
    labelList:[],
    annotationsList:[],
    rules: {
      name: [
            {required: true, message: '请输入PV名称', trigger: 'blur'}
        ],
      capacity: [
          {required: true, message: '请输入PV大小', trigger: 'blur'}
      ],
      storageClassName: [
          {required: true, message: '请输入存储类名称', trigger: 'blur'}
      ],
      server: [
          {required: true, message: '请输入NFS地址', trigger: 'blur'}
      ],
      path: [
          {required: true, message: '请输入NFS路径', trigger: 'blur'}
      ],
    },
    accessModes: [
      {
        value: 'ReadWriteMany',
        label: '多节点读写',
      },
      {
        value: 'ReadWriteOnce',
        label: '单节点读写',
      },
      {
        value: 'ReadOnlyMany',
        label: '多节点只读',
      },
      {
        value: 'ReadWriteOncePod',
        label: '单Pod读写',
      },
    ],
    reclaimPolicy: [
      {
        value: 'Retain',
        label: '保留数据',
      },
      {
        value: 'Delete',
        label: '删除数据',
      },
      {
        value: 'Recycle',
        label: '回收数据',
      },
    ]
  }
})
const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
let yamlContent = ref('')
let showDetail = ref(false)

const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/pv/list',
        query: {
          clusterId: data.clusterId,
        }
      })
    })
    .catch(() => {
      return
    })
}

const submitHandler = (tag) => {
  console.log('tag:', tag)
  console.log('item:', data.item)
  //把list转成object
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationsList)
  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      item: data.item,
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
          // loading.value = false
          // emits('rollback')
        })
  } else {
      // 创建用户，异步的
      updateHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}

const submit = (tag)=> {
    itemRef.value.validate((valid)=>{
        // valid => true
        if(!valid){
        ElMessage({
                    message: "请完善表单内容",
                    type: 'warning',
                })
        }else {
          submitHandler(tag)
        }
    })
}
const rollback = (clusterId,)=>{
  console.log('cluster id:', clusterId)
  data.clusterId = clusterId
  // data.namespace = namespace
  // data.item.metadata.namespace = namespace
}

onBeforeMount(()=>{
  if (props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationsList = object2List(data.item.metadata.annotations)
    if (data.item.spec.nfs != undefined){
      console.log('当前编辑的是nfs')
      data.options.pvType = 'nfs'
    }else {
      data.options.pvType = ''
    }
  }
})  
const {options,item,clusterId,namespace} = toRefs(data)

</script>

<template>
  <CreateOrEditFrame
  :show-namespace="false"
  :cluster-readonly="props.method == 'Update'"
  @clusterChangedRollback="rollback"
  >
  <!-- 头部插入内容 -->

   <template #main>
    <el-form :model="item"
    label-width="true"
    ref="itemRef">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="基本配置" name="basic" style="height: 240px;">
        <el-row :gutter="5">
          <el-col :span="8">
              <el-form-item  :rules="options.rules.name" label="PV名称" prop="metadata.name" required>
                  <el-input style="width: 280px;"  :disabled="props.method == 'Update'" v-model="item.metadata.name"></el-input>
              </el-form-item>
          </el-col>
          <!-- 选择存储类型 -->
          <el-col :span="8" v-if="options.pvType == 'nfs'">
              <el-form-item  label="存储类型" prop="">
                <el-select 
                  v-model="options.pvType" 
                  style="width: 280px;"
                  placeholder="选择存储类型">
                    <el-option 
                    v-for="item in ['nfs']" 
                    :key="item" 
                    :label="item" 
                    :value="item">
                    </el-option>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item  :rules="options.rules.capacity" label="大小" prop="spec.capacity.storage" required>
                  <el-input style="width: 220px;" v-model="item.spec.capacity.storage"></el-input>
              </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="8">
              <el-form-item  :rules="options.rules.storageClassName" label="存储类名称" prop="spec.storageClassName" required>
                  <el-input style="width: 280px;" v-model="item.spec.storageClassName" placeholder="请输入存储类的名称,为空时为资源名称"></el-input>
              </el-form-item>
          </el-col>
          <!-- 访问策略 -->
          <el-col :span="8">
              <el-form-item  label="访问策略" prop="">
                <el-select 
                  v-model="item.spec.accessModes" 
                  multiple
                  collapse-tags
                  style="width: 280px;"
                  placeholder="选择访问策略">
                    <el-option 
                    v-for="item in options.accessModes" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item  label="回收策略" prop="">
                <el-select 
                  v-model="item.spec.persistenceVolumeReclaimPolicy" 
                  style="width: 220px;"
                  multiple
                  placeholder="选择回收策略">
                    <el-option 
                    v-for="item in options.reclaimPolicy" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
          </el-col>
        </el-row>
        <!-- 存储相关配置 -->
         <el-row :gutter="5" v-if="options.pvType == 'nfs'">
          <el-col :span="8">
              <el-form-item  :rules="options.rules.server" label="NFS地址" prop="spec.nfs.server" required>
                  <el-input  style="width: 280px;" v-model="item.spec.nfs.server"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item  :rules="options.rules.path" label="NFS路径" prop="spec.nfs.path" required>
                  <el-input  style="width: 280px;" v-model="item.spec.nfs.path"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item  label="只读" prop="">
                  <el-switch style="width: 220px;" v-model="item.spec.nfs.readOnly"></el-switch>
              </el-form-item>
          </el-col>
         </el-row>
      </el-tab-pane>
      <el-tab-pane label="注释及标签" name="labels">
        <el-tabs v-model="labelConfig" tabPosition="left">
            <el-tab-pane label="标签配置" name="labels">
              <Table :list="options.labelList"></Table>
            </el-tab-pane>
            <el-tab-pane label="注释配置" name="annos">
              <Table :list="options.annotationsList"></Table>
            </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>

    <!-- yaml,创建 -->
    <el-form-item class="button-container" style="margin-top: 10px;">
      <el-button @click="submit('yaml')">Yaml</el-button>
      <el-button type="primary" @click="submit()">
        {{ props.method=="Update" ? "更新" : "创建" }}
      </el-button>

     </el-form-item>
    </el-form>
   </template>

  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  :method="props.method"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
</template>

<style scoped>
.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中（如果需要） */
  gap: 10px;               /* 按钮之间的间距 */
}
</style>
